﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.ExtentionMethods;

namespace Happy.Query
{
    /// <summary>
    /// Where 子句，包含 WHERE。
    /// </summary>
    public sealed class WhereClause
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        public WhereClause(string clause, object[] arguments)
        {
            this.Clause = clause;
            this.Arguments = arguments;
        }

        /// <summary>
        /// 子句。
        /// </summary>
        public string Clause { get; private set; }

        /// <summary>
        /// 子句的参数。
        /// </summary>
        public object[] Arguments { get; private set; }

        /// <summary>
        /// 工厂方法。
        /// </summary>
        public static WhereClause Create(string whereClause, object[] whereClauseArguments)
        {
            return new WhereClause(whereClause, whereClauseArguments);
        }

        /// <summary>
        /// 工厂方法。
        /// </summary>
        public static WhereClause Create(object condition)
        {
            condition.MustNotNull("condition");

            var properties = condition.GetType().GetProperties();
            var whereClause = new StringBuilder();
            var whereClauseArguments = new object[properties.Length];

            int parameterIndex = 0;
            for (var i = 0; i < properties.Length; i++)
            {
                if (i != 0)
                {
                    whereClause.Append(" AND ");
                }

                var value = properties[i].GetValue(condition);
                if (value == null)
                {
                    whereClause.AppendFormat("{0} IS NULL", properties[i].Name);
                }
                else
                {
                    whereClause.AppendFormat("{0} = @{1}", properties[i].Name, i);
                    whereClauseArguments[i] = value;
                    parameterIndex++;
                }
            }

            return new WhereClause(whereClause.ToString(), whereClauseArguments);
        }
    }
}
